package com.zhuiyun.project.api.submitrecord.service.impl;



import com.zhuiyun.project.api.recording.entiy.TransactionHistory;
import com.zhuiyun.project.api.recording.mapper.TransactionHistoryMapper;
import com.zhuiyun.project.api.recording.model.TransactionHistoryModel;
import com.zhuiyun.project.api.submitrecord.entity.SubmitRecord;
import com.zhuiyun.project.api.submitrecord.mapper.SubmitMapper;
import com.zhuiyun.project.api.submitrecord.service.ISubmitService;
import com.zhuiyun.project.api.sysUser.entiy.SysUser;
import com.zhuiyun.project.api.sysUser.mapper.SysUserMapper;
import com.zhuiyun.project.api.sysUser.service.SysUserService;
import com.zhuiyun.project.common.errorCode.EmErrorCode;
import com.zhuiyun.project.common.response.CommonResult;
import com.zhuiyun.project.util.UserUtils;
import com.zhuiyun.project.util.constants.CommonConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName LotteryServiceImpl
 * @Description TODO
 * @Author 17179
 * @Date 2024/7/16 15:49
 **/
@Service
public class SubmitServiceImpl implements ISubmitService {

    @Autowired
    private SubmitMapper submitMapper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TransactionHistoryMapper transactionHistoryMapper;
    @Override
    public CommonResult saveSubmitRecord(SubmitRecord submit) {
        String phone = UserUtils.getUser().getPhone();
        int count  = submitMapper.selectCountByPhoneAndTypeIndexAndProjectIndex(phone,submit.getLotteryTypeIndex(),submit.getProjectNameIndex());
        if(count==0){
            BigDecimal bigDecimal = new BigDecimal(0.00);
            submit.setProfit(bigDecimal);
            submit.setPhoneNumber(phone);
            submit.setCreateTime(new Date());
            submit.setFlag(0); // 默认不中
            submit.setCount(0); // 查看次数
            int i = submitMapper.insert(submit);
            if(i>0){
                return CommonResult.ok(EmErrorCode.SAVE_OK);
            }else{
                return CommonResult.ok(EmErrorCode.SAVE_ERROR);
            }
        }else{
            return CommonResult.error("您已经发布了该项目！");
        }
    }


    /**
     * 获取自己的提交记录
     * @return
     */
    @Override
    public CommonResult getMySubmitRecord() {
        String phone = UserUtils.getUser().getPhone();
        List<SubmitRecord> list = submitMapper.getMySubmitRecord(phone);
        return CommonResult.ok(list);
    }

    /**
     * 按照中奖频率的高低查找推荐数据
     * @param lotteryTypeIndex
     * @return
     */
    @Override
    public CommonResult getSubmitRecordByType(Integer lotteryTypeIndex,Integer projectNameIndex,String lotteryNo) {
        List<Map> list =submitMapper.getSubmitRecordByType(lotteryTypeIndex,projectNameIndex,lotteryNo);
        return CommonResult.ok(list);
    }

    @Override
    public CommonResult getSubmitRecordByPhoneAndType(Integer lotteryTypeIndex, Integer projectNameIndex, String phoneNumber) {
        List<Map> list =submitMapper.getSubmitRecordByPhoneAndType(lotteryTypeIndex,projectNameIndex,phoneNumber);
        return CommonResult.ok(list);
    }

    @Override
    public CommonResult getMyExperience() {
        String phone = UserUtils.getUser().getPhone();
        Map map =  submitMapper.getMyExperience(phone);
        return CommonResult.ok(map);
    }

    @Override
    public List<SubmitRecord> getLastSubmit(String type, String lastLotteryNo) {
        return submitMapper.getLastSubmit(type,lastLotteryNo);
    }

    @Override
    public int updateSubmitFlag(SubmitRecord submitRecord) {
        return submitMapper.updateByPrimaryKey(submitRecord);
    }

    @Override
    @Transactional
    public synchronized  CommonResult payCommission(SubmitRecord submit) {
        // 检查扣款金额是否大于0
        if (submit.getCommission().compareTo(BigDecimal.ZERO) <= 0) {
           return  CommonResult.error("扣费金额必须大于0");
        }
        // 获取用户信息
        SysUser sysUser = sysUserMapper.selectUserById(UserUtils.getUser().getId());
        // 检查余额是否足够，确保扣款后余额大于0
        if (sysUser.getAmount().compareTo(submit.getCommission()) < 0) {
            return  CommonResult.error("余额不足");
        }
        // 更新用户余额
        int rowsAffected = sysUserMapper.updateUserAmount(sysUser.getId(), submit.getCommission());
        // 将金币存储到admin账户下，开奖后计算退款或者分账
        int i1 = sysUserMapper.updateAdminAmount(1, submit.getCommission());
        // 观看记录+1
        int i = submitMapper.updateCountIncr(submit.getId());
        // 记录
        TransactionHistory transactionHistory=new TransactionHistory();
        transactionHistory.setCreateTime(new Date());
        transactionHistory.setState(CommonConstants.CONSUME);
        transactionHistory.setOptionUser(sysUser.getPhone());
        transactionHistory.setRechargeUserPhone(sysUser.getPhone());
        transactionHistory.setAmount(submit.getCommission());
        transactionHistory.setProductId(submit.getId());// 商品id
        transactionHistory.setSeparateFlag(0);
        // 存入消费记录
        int  j =transactionHistoryMapper.insert(transactionHistory);
        if (rowsAffected == 0) {
           return CommonResult.error("扣款失败，余额不足");
        }
        return CommonResult.ok();
    }

    @Override
    public CommonResult getSubmitRecordByTypeAndToday(Integer lotteryTypeIndex, Integer projectNameIndex, String lotteryNo) {
        List<Map> list =submitMapper.getSubmitRecordByTypeAndToday(lotteryTypeIndex,projectNameIndex,lotteryNo);
        return CommonResult.ok(list);
    }


}